import {
  PlusOutlined,
  DeleteOutlined,
  CloudDownloadOutlined,
  CloudUploadOutlined,
  EditOutlined,
  CodeOutlined,
  DownOutlined,
  InsertRowBelowOutlined,
  SyncOutlined,
  HistoryOutlined,
  ThunderboltFilled,
  FolderOpenFilled,
  EyeOutlined,
} from '@ant-design/icons';
import { Button, Dropdown, Modal, Popconfirm, Tag } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { PropertyItem, ModelItem, ModelParams } from '@/services/develop/types';
import { ProFormSwitch, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import EditForm from '@/components/EditForm';
import { ModelColumns } from './columns';
import { handleAdd, handleUpdate, handleRemove } from './action';
import { pageModel } from '@/services/develop/model';
import SzhomeTable from '@/components/Custom/SzhomeTable';
import Property from '../property';
import { listProperty } from '@/services/develop/property';
import SzhomeSelect from '@/components/Custom/SzhomeSelect';
import { listDatasource } from '@/services/develop/datasource';
import { ProFormSegmented } from '@ant-design/pro-components';
import { listProject } from '@/services/develop/project';
import { getDictValues } from '@/services/system/dictValue';
import ModelScript from './ModelScript';
import Preview from './Preview';

const layout = await getDictValues('form.layout');

const Model: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<ModelItem>();
  const [selectedRowsState, setSelectedRows] = useState<ModelItem[]>([]);
  const [settingVisible, setSettingVisible] = useState<boolean>(false);
  const [properties, setProperties] = useState<PropertyItem[]>([]);
  const [scriptVisible, setScriptVisible] = useState<boolean>(false);
  const [previewVisible, setPreviewVisible] = useState<boolean>();
  const [modelIds, setModelIds] = useState<string[]>([]);

  const columns: ProColumns<ModelItem>[] = [
    ...ModelColumns,
    {
      title: '操作',
      align: 'center',
      dataIndex: 'option',
      valueType: 'option',
      width: 260,
      render: (_, record) => [
        <a
          key={'edit-' + record.id}
          onClick={() => {
            setCurrentRow(record);
            handleModalVisible(true);
          }}
        >
          <EditOutlined />
          &nbsp;编辑
        </a>,
        <a
          key={'setting-' + record.id}
          onClick={() => {
            setSettingVisible(true);
            listProperty({ modelId: record.id }).then((res) => {
              res.data.forEach((p) => {
                p.validateLength = [];
                if (p.validateLengthMin || p.validateLengthMax) {
                  if (p.validateLengthMin) p.validateLength[0] = p.validateLengthMin;
                  if (p.validateLengthMax) p.validateLength[1] = p.validateLengthMax;
                }

                p.validateValue = [];
                if (p.validateValueMin || p.validateValueMax) {
                  if (p.validateValueMin) p.validateValue[0] = p.validateValueMin;
                  if (p.validateValueMax) p.validateValue[1] = p.validateValueMax;
                }
              });
              setProperties(res.data);
            });
          }}
        >
          <InsertRowBelowOutlined />
          &nbsp;字段
        </a>,
        <Dropdown
          key="more"
          menu={{
            items: [
              {
                key: 'code',
                label: '生成代码',
                icon: <ThunderboltFilled />,
                onClick: () => {
                  Modal.confirm({
                    title: (
                      <>
                        您确定要生成模型 <Tag color="error">{record.tableName}</Tag>的代码吗？
                      </>
                    ),
                    onOk: async () => {
                      // window.open('/api/szhome-develop/develop/generator/model/' + record.id, '_blank');
                      window.location.href =
                        '/api/szhome-develop/develop/generator/model/' + record.id;
                    },
                    okText: '确定',
                    cancelText: '取消',
                  });
                },
              },
              {
                key: 'preview',
                label: '生成预览',
                icon: <EyeOutlined />,
                onClick: () => {
                  setModelIds([record.id]);
                  setPreviewVisible(true);
                },
              },
              {
                key: 'history',
                label: '历史记录',
                icon: <HistoryOutlined />,
              },
              {
                type: 'divider',
              },
              {
                key: 'script',
                label: '常用脚本',
                icon: <CodeOutlined />,
                onClick: () => {
                  setCurrentRow(record);
                  setScriptVisible(true);
                },
              },
              {
                key: 'sync',
                label: '同步字段',
                icon: <SyncOutlined />,
              },
              {
                key: 'index',
                label: '索引维护',
                icon: <FolderOpenFilled />,
              },
              {
                type: 'divider',
              },
              {
                key: 'delete',
                label: '删除模型',
                icon: <DeleteOutlined />,
                danger: true,
                onClick: async () => {
                  Modal.confirm({
                    title: (
                      <>
                        确定要删除模型表 <Tag color="error">{record.tableName}</Tag>吗？
                      </>
                    ),
                    onOk: async () => {
                      await handleRemove([record]);
                      setSelectedRows([]);
                      actionRef.current?.reloadAndRest?.();
                    },
                    okText: '确定',
                    cancelText: '取消',
                  });
                },
              },
            ],
          }}
        >
          <a>
            更多 <DownOutlined />
          </a>
        </Dropdown>,
      ],
    },
  ];

  return (
    <PageContainer>
      <SzhomeTable<ModelItem, ModelParams>
        actionRef={actionRef}
        request={pageModel}
        columns={columns}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCurrentRow(undefined);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新增
          </Button>,
          <Button
            key="primary"
            disabled={selectedRowsState?.length == 0}
            onClick={() => {
              Modal.confirm({
                title: <>您确定要生成{selectedRowsState.length}个模型的代码吗？</>,
                onOk: async () => {
                  // window.open('/api/szhome-develop/develop/generator/model/' + record.id, '_blank');
                  window.location.href =
                    '/api/szhome-develop/develop/generator/model/' +
                    selectedRowsState.map((item) => item.id);
                },
                okText: '确定',
                cancelText: '取消',
              });
            }}
          >
            <ThunderboltFilled /> 生成代码
          </Button>,

          <Button
            key="batch-preview"
            disabled={selectedRowsState?.length == 0}
            onClick={() => {
              setModelIds(selectedRowsState.map((item) => item.id));
              setPreviewVisible(true);
            }}
          >
            <EyeOutlined /> 生成预览
          </Button>,
          <Popconfirm
            key={'batch_remove'}
            disabled={selectedRowsState?.length == 0}
            title={'您确定要删除已选' + selectedRowsState?.length + '条模型数据吗？'}
            onConfirm={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            okText="Yes"
            cancelText="No"
          >
            <Button key="batch_remove" danger disabled={selectedRowsState?.length == 0}>
              <DeleteOutlined />
              删除
            </Button>
          </Popconfirm>,

          <Button
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <CloudDownloadOutlined /> 导出
          </Button>,
          <Dropdown.Button
            key="import"
            menu={{
              items: [
                { key: 'ddl', label: 'DDL 脚本' },
                { key: 'excel', label: 'Excel 文件' },
                { key: 'json', label: 'JSON 文件' },
              ],
            }}
          >
            <CloudUploadOutlined />
            导入
          </Dropdown.Button>,
        ]}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />

      {/* 新增、编辑 */}
      <EditForm
        visible={createModalVisible}
        name="模型"
        model={currentRow || { id: undefined }}
        onAdd={handleAdd}
        onUpdate={handleUpdate}
        afterEdit={() => {
          setCurrentRow(undefined);

          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
        onCancel={handleModalVisible}
      >
        <ProFormText name="id" hidden={true} />
        <SzhomeSelect
          label="数据源"
          name="datasourceId"
          disabled={currentRow?.id == null}
          fn={listDatasource}
          colProps={{ span: 12 }}
        />
        <SzhomeSelect label="所属工程" name="projectId" fn={listProject} colProps={{ span: 12 }} />
        <ProFormText label="表名" name="tableName" colProps={{ span: 12 }} />
        <ProFormText label="表前缀" name="tablePrefix" colProps={{ span: 12 }} />
        <ProFormTextArea label="表注释" name="comments" />
        <ProFormText label="模型编码" name="code" colProps={{ span: 12 }} />
        <ProFormText label="模型名称" name="name" colProps={{ span: 12 }} />
        <ProFormText label="模块编码" name="module" colProps={{ span: 12 }} />
        <ProFormText label="作者" name="author" colProps={{ span: 12 }} />
        <ProFormSwitch label="树形模型" name="tree" colProps={{ span: 6 }} />
        <ProFormSwitch label="是否分页" name="page" colProps={{ span: 6 }} />
        <ProFormSegmented
          label="表单布局"
          fieldProps={{
            colSpan: 12,
          }}
          name="layout"
          valueEnum={layout}
        />
        <ProFormTextArea label="备注" name="remark" />
      </EditForm>

      {/* 属性设置 */}
      <Property
        open={settingVisible}
        modelId={currentRow?.id || '0'}
        data={properties}
        changeOpen={setSettingVisible}
      />

      {/* 常用脚本 */}
      <Modal
        title="常用脚本"
        open={scriptVisible}
        width={1440}
        onCancel={() => setScriptVisible(false)}
        destroyOnClose={true}
      >
        {currentRow?.id && <ModelScript modelId={currentRow?.id} />}
      </Modal>

      {/* 代码预览 */}
      <Modal
        title={
          <>
            <EyeOutlined />
            &nbsp;&nbsp;生成预览
          </>
        }
        open={previewVisible}
        width={1440}
        onCancel={() => setPreviewVisible(false)}
        destroyOnClose={true}
      >
        <Preview modelId={modelIds} />
      </Modal>
    </PageContainer>
  );
};

export default Model;
